/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ModuloConfiguracion;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import Modelo.*;
import Modelo.DAL.Grupo_DAO;
import Acceso.Security;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMessage;

/**
 *
 * @author josmary
 */
public class agregarGrupoAction extends org.apache.struts.action.Action {

    /* forward name="success" path="" */
    private final static String SUCCESS = "success";
    private final static String FAILURE = "failure";
    private static final String[] ALLOWED = {"Administrador", "Gestionar Grupos"};

    boolean validarId(ActionErrors errors, String cadena, String err, HttpServletRequest request, Pattern p) {
        Matcher m;
        m = p.matcher(cadena);
        if (!m.matches()) {
            errors.add(err, new ActionMessage("errors.invalid_idGrupo"));
            saveErrors(request, errors);
            return true;
        }
        return false;
    }

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        if (!Security.validateSession(request, ALLOWED)) {
            Security.privilegeError(response);
            return mapping.findForward("errorPriv");
        }

        ActionErrors errors = new ActionErrors();
        agregarGrupoForm formBean = (agregarGrupoForm) form;
        String sede = formBean.getSede();
        String id = formBean.getId();
        String tipo = formBean.getTipo();
        Pattern p;
        Matcher m;
        boolean hayError = false;



        if (formBean.getId() == null || formBean.getId().length() < 1) {
            System.out.print("Entre a verificacion Nula");
            errors.add("id_vacio", new ActionMessage("errors.id_vacio"));
            saveErrors(request, errors);
            hayError = true;

            return mapping.findForward(FAILURE);
        }

        p = Pattern.compile("[A-Z][0-9]*");
        hayError = validarId(errors, id, "invalid_idGrupo", request, p);

        if (hayError) {
            formBean.setId(null);
            return mapping.findForward(FAILURE);
        }

        if (!hayError) {

            Grupo g = new Grupo();
            g.setSede(sede);
            g.setIdGrupo(id);
            g.setTipoGrupo(tipo);
            Grupo_DAO conexgrupo = new Grupo_DAO();

            if (conexgrupo.comprobarGrupo(g)) {
                formBean.setError("El Grupo: " + g.getIdGrupo() + " ya existe. ");
                errors.add("grupo_ya_esta", new ActionMessage("errors.grupo_ya_esta"));
                saveErrors(request, errors);
                System.out.print("Comprobando Grupo en el Action");
                formBean.setId(null);
                return mapping.findForward(FAILURE);
            }

            if (!conexgrupo.insertarGrupo(g)) {
                formBean.setError("Error agregando el Grupo, intente de nuevo.");
                System.out.print("Insertando Grupo en el Action");
                formBean.setId(null);

                return mapping.findForward(FAILURE);
            }
        }
        formBean.setId(null);

        return mapping.findForward(SUCCESS);
    }
}
